#!/usr/bin/env bash
set -euo pipefail

# 渲染规则文件：将 {{KEY}} 按 config/rules.env 替换，输出到 .tmp/rendered_rules

ROOT_DIR="$(cd "$(dirname "$0")"/.. && pwd)"
ENV_FILE="$ROOT_DIR/config/rules.env"
SRC_DIR="$ROOT_DIR/rules"
OUT_DIR="$ROOT_DIR/.tmp/rendered_rules"

usage() {
  echo "Usage: $0 [SRC_DIR] [OUT_DIR]"
  echo "Default SRC_DIR=$SRC_DIR"
  echo "Default OUT_DIR=$OUT_DIR"
}

if [[ "${1:-}" != "" ]]; then SRC_DIR="$1"; fi
if [[ "${2:-}" != "" ]]; then OUT_DIR="$2"; fi

mkdir -p "$OUT_DIR"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Config not found: $ENV_FILE" >&2
  exit 1
fi

# 读取 env 键值（忽略注释/空行）
declare -A KV
while IFS='=' read -r key value; do
  [[ -z "$key" ]] && continue
  [[ "$key" =~ ^# ]] && continue
  # 展开变量（支持 ${MODULE_NAME} 等）
  eval "value=\"$value\""
  KV[$key]="$value"
  # 将键值导入环境，保证后续派生键可扩展
  export "$key=$value"
done < <(grep -E '^[A-Z_]+=' "$ENV_FILE")

render_file() {
  local src="$1" rel out
  rel="${src#$SRC_DIR/}"
  out="$OUT_DIR/$rel"
  mkdir -p "$(dirname "$out")"
  cp "$src" "$out"
  for k in "${!KV[@]}"; do
    local v="${KV[$k]}"
    # 使用 perl 进行安全替换，支持 / 与空格
    perl -CS -pi -e "s~\{\{$k\}\}~$v~g" "$out"
  done
}

export -f render_file

mapfile -t files < <(find "$SRC_DIR" -type f -name "*.md")
for f in "${files[@]}"; do
  render_file "$f"
done

echo "Rendered rules into: $OUT_DIR";
